package com.xbts.quartz.task;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huaweicloud.sdk.ecs.v2.model.ListServersDetailsResponse;
import com.huaweicloud.sdk.ecs.v2.model.ServerDetail;
import com.xbts.common.core.domain.entity.SysUser;
import com.xbts.common.enums.ServerStatusEnum;
import com.xbts.common.enums.ShoppingCarEnums;
import com.xbts.common.enums.SmsTemplateEnum;
import com.xbts.common.utils.SnowFlakeUtil;
import com.xbts.common.utils.bean.BeanUtils;
import com.xbts.system.domain.CnOrder;
import com.xbts.system.domain.CnOrderItem;
import com.xbts.system.domain.CnShoppingCar;
import com.xbts.system.domain.CnUserCloudServersRelation;
import com.xbts.system.domain.dto.ListServersDetailsRequestDTO;
import com.xbts.system.domain.dto.SmsDTO;
import com.xbts.system.enums.OrderStatusEnum;
import com.xbts.system.enums.OrderTypeEnum;
import com.xbts.system.mapper.SysUserMapper;
import com.xbts.system.module.payment.enums.PaymentMethodEnum;
import com.xbts.system.module.payment.service.ICnWalletLogService;
import com.xbts.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 自动续费任务
 *
 * @Author llk
 * @Date 2023/8/25 13:36
 */
@Slf4j
public class AutoRenewTask {

    public void autoRenew(ICnUserCloudServersRelationService cnUserCloudServersRelationService,
                          SysUserMapper userMapper, ISmsService smsService, ICnOrderService cnOrderService,
                          ICnOrderItemService cnOrderItemService, ICnWalletLogService cnWalletLogService) {
                          // 查询所有离到期还有十天之内的的订单
                          QueryWrapper<CnUserCloudServersRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATEDIFF(expiration_time, CURDATE()) expiration_day,id,user_id,relation_id," +
                "auto_renew,period_num,expiration_time,buying_time,shopping_car_enums,order_abstract,create_by,period_type" +
                ",create_time,update_by,update_time,update_price,discount_price,original_price ");
        queryWrapper.between(" DATEDIFF(expiration_time, CURDATE())", 0, 10);
        List<CnUserCloudServersRelation> list = cnUserCloudServersRelationService.list(queryWrapper);

        // 遍历订单，调用续费接口
        for (CnUserCloudServersRelation cnUserCloudServersRelation : list) {
            SysUser sysUser = userMapper.selectUserById(cnUserCloudServersRelation.getUserId());

            // 自动续费
            if (cnUserCloudServersRelation.getAutoRenew()) {
                cnUserCloudServersRelationService.autoRenew(cnUserCloudServersRelation.getId().toString());
/*                // 判断余额是否充足
                if (sysUser.getUserWallet().compareTo(cnUserCloudServersRelation.getUpdatePrice()) > 0) { // 余额充足
                    // 提前一天生成订单
                    if (cnUserCloudServersRelation.getExpirationDay() != 1) {
                        continue;
                    }
                    // 生成订单
                    CnOrderItem orderItem = createOrder(cnUserCloudServersRelation, sysUser, cnOrderService, cnOrderItemService);
                    // 扣除余额
                    cnWalletLogService.updateUserBalanceAndLog(cnUserCloudServersRelation.getUserId(),
                            cnUserCloudServersRelation.getUpdatePrice().negate(),
                            PaymentMethodEnum.WALLET.name(), null, orderItem.getShoppingCarEnums()
                    , orderItem.getSn(), "autoRenew");

                    // 华为云续费
                } else { // 余额不足，10天之类发送短信提醒
                    String msg = String.format("服务器ID为【%s】%s 天到期，到期停止服务，账号余额不足，请提前充值余额",
                            cnUserCloudServersRelation.getRelationId(),
                            cnUserCloudServersRelation.getExpirationDay() == 0 ? "今" : "还有" + cnUserCloudServersRelation.getExpirationDay());
                    log.info("自动续费msg = {}", msg);*/
//                    // TODO 发送短信
//                    SmsDTO smsDTO = new SmsDTO(msg, sysUser.getPhonenumber());
////                    smsService.sendMsg(smsDTO, SmsTemplateEnum.EXPIRATION_NOTICE);
//                }
                // 不是自动续费
            } else {
                String msg = String.format("服务器ID为【%s】%s天到期，到期停止服务", cnUserCloudServersRelation.getRelationId(),
                        cnUserCloudServersRelation.getExpirationDay() == 0 ? "今" : "还有" + cnUserCloudServersRelation.getExpirationDay());
                log.info("不自动续费msg = {}", msg);
                // 发送短信
                SmsDTO smsDTO = new SmsDTO(msg, sysUser.getPhonenumber());
                smsService.sendMsg(smsDTO, SmsTemplateEnum.EXPIRATION_NOTICE);
            }
        }

    }

    private void createCnShoppingCar(ICnShoppingCarService cnShoppingCarService, CnUserCloudServersRelation cnUserCloudServersRelation) {
        CnShoppingCar cnShoppingCar = new CnShoppingCar();
        BeanUtils.copyBeanProp(cnShoppingCar, cnUserCloudServersRelation);
        // 继续使用修改后的价格
//        cnShoppingCar.setShoppingCarType(ShoppingCarTypeEnum.SYSTEM.name());
//        cnShoppingCar.setCnUserCloudServersRelationId(cnUserCloudServersRelation.getId());
        cnShoppingCarService.insertCnShoppingCar(cnShoppingCar);
    }

    /**
     * 生成订单
     *
     * @param cnUserCloudServersRelation 用户关系表
     */
    private CnOrderItem createOrder(CnUserCloudServersRelation cnUserCloudServersRelation, SysUser sysUser,
                             ICnOrderService cnOrderService, ICnOrderItemService cnOrderItemService) {
        Date date = new Date();

        Long orderId = SnowFlakeUtil.getSnowFlakeId();

        // 子订单项
        CnOrderItem cnOrderItem = genCnOrderItem(cnUserCloudServersRelation);

        BigDecimal totalOriginalPrice = BigDecimal.ZERO; // 总原始价格
        BigDecimal totalDiscountPrice = BigDecimal.ZERO; // 总优惠价格
        BigDecimal totalUpdatePrice = BigDecimal.ZERO; // 总修改后价格

        totalOriginalPrice = totalOriginalPrice.add(cnOrderItem.getOriginalPrice());
        totalDiscountPrice = totalDiscountPrice.add(cnOrderItem.getDiscountPrice());
        totalUpdatePrice = totalUpdatePrice.add(cnOrderItem.getUpdatePrice());
        cnOrderItem.setOrderId(orderId);
        cnOrderItem.setUserId(cnUserCloudServersRelation.getUserId());
        cnOrderItem.setCreateTime(date);
        cnOrderItem.setCnUserCloudServersRelationId(cnUserCloudServersRelation.getId());

        // 订单
        CnOrder cnOrder = new CnOrder();
        cnOrder.setOrderId(orderId);
        cnOrder.setUserId(cnUserCloudServersRelation.getUserId());
        cnOrder.setUserName(sysUser.getNickName());
        cnOrder.setOrderStatus(OrderStatusEnum.IN_PROGRESS);
        cnOrder.setShoppingCarType(OrderTypeEnum.SYSTEM.name());

        // 生成订单号
        cnOrder.setSn("SN" + SnowFlakeUtil.getSnowFlakeId());
        cnOrder.setPaymentTime(date);
        cnOrder.setOriginalPrice(totalOriginalPrice);
        cnOrder.setDiscountPrice(totalDiscountPrice);
        cnOrder.setUpdatePrice(totalUpdatePrice);
        cnOrderService.save(cnOrder);

        cnOrderItem.setSn(cnOrder.getSn());
        // 保存子订单
        cnOrderItemService.save(cnOrderItem);

        return cnOrderItem;
    }

    /**
     * 生成订单项
     *
     * @param cnUserCloudServersRelation 用户关系表
     * @return
     */
    private CnOrderItem genCnOrderItem(CnUserCloudServersRelation cnUserCloudServersRelation) {
        CnOrderItem cnOrderItem = new CnOrderItem();
        BeanUtils.copyProperties(cnUserCloudServersRelation, cnOrderItem);
        cnOrderItem.setShoppingCarType(OrderTypeEnum.SYSTEM.name());
        return cnOrderItem;
    }

    /**
     * 过期的服务器，将状态修改为过期
     */
    public void expirationAutoRenew(ICnUserCloudServersRelationService cnUserCloudServersRelationService, ICloudControlService cloudControlService) {
        List<CnUserCloudServersRelation> saveLst = new ArrayList<>();
        QueryWrapper<CnUserCloudServersRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lt(" DATEDIFF(expiration_time, CURDATE())", 0);
        List<CnUserCloudServersRelation> list = cnUserCloudServersRelationService.list(queryWrapper);
        list.forEach(f -> log.info("过期的服务器 = " + f.getRelationId() + ",用户id = " + f.getUserId()));
        list.forEach(cnUserCloudServersRelation -> {
            cnUserCloudServersRelation.setStatus(ServerStatusEnum.EXPIRED);
            saveLst.add(cnUserCloudServersRelation);
        }); // 批量更新
        if (saveLst.size() > 0) {
            cnUserCloudServersRelationService.updateBatchById(saveLst);
        }
        // 更新 jsonStr 字符串 更新服务器状态json
        LambdaQueryWrapper<CnUserCloudServersRelation> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CnUserCloudServersRelation::getStatus, ServerStatusEnum.ACTIVE);
        queryWrapper1.eq(CnUserCloudServersRelation::getShoppingCarEnums, ShoppingCarEnums.CLOUD_SERVER);
        List<CnUserCloudServersRelation> relationList = cnUserCloudServersRelationService.list(queryWrapper1);
        if (!relationList.isEmpty()) {
            // 服务器id
            String serviceIds = relationList.stream().map(CnUserCloudServersRelation::getRelationId).collect(Collectors.joining(","));
            ListServersDetailsResponse listServersDetailsResponse = cloudControlService.listServersDetails(new ListServersDetailsRequestDTO(serviceIds));
            if (null != listServersDetailsResponse && listServersDetailsResponse.getServers().size() > 0) {
                List<ServerDetail> servers = listServersDetailsResponse.getServers();
                Map<String, ServerDetail> map = servers.stream().collect(Collectors.toMap(ServerDetail::getId, Function.identity()));
                for (CnUserCloudServersRelation cnUserCloudServersRelation : relationList) {
                    if (map.containsKey(cnUserCloudServersRelation.getRelationId())) {
                        ServerDetail serverDetail = map.getOrDefault(cnUserCloudServersRelation.getRelationId(), null);
                        if (null != serverDetail) {
                            cnUserCloudServersRelation.setJsonStr(JSONObject.toJSONString(serverDetail));
                        }
                    }
                }
            }
            // 批量更新
            cnUserCloudServersRelationService.updateBatchById(relationList);
        }
    }

}
